package dy.com.udp.广播;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.UUID;

public class Server {
    public static void main(String[] args) throws IOException {
        //得到sn
        String sn = UUID.randomUUID().toString();
        ServerThread thread = new ServerThread(sn);
        thread.start();
        //阻塞，当有输入时，退出
        System.in.read();
        thread.exit();
    }

    private static class ServerThread extends Thread {
        String sn;
        boolean flag = true;
        DatagramSocket ds = null;

        ServerThread(String sn) {
            this.sn = sn;
        }

        @Override
        public void run() {
            //监听端口
            System.out.println("服务端开始监听");
            try {
                ds = new DatagramSocket(20000);
                System.out.println(flag);
                while (flag) {
                    byte[] buffer = new byte[512];
                    DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
                    ds.receive(dp);

                    String ip = dp.getAddress().getHostAddress();
                    int port = dp.getPort();
                    int len = dp.getLength();
                    String data = new String(dp.getData(), 0, len);

                    System.out.println("服务端收到消息，ip：" + ip + ",端口：" + port + ",数据:" + data);
                    //解析消息中的端口号
                    int targetPort = MessageCreator.parsePort(data);
                    if (targetPort != -1) {
                        //将本服务器的信息包装
                        String res = MessageCreator.buildWithSn(sn);
                        byte[] r = res.getBytes();
                        DatagramPacket resDp = new DatagramPacket(r, r.length, dp.getAddress(), targetPort);
                        ds.send(resDp);
                    }

                }

            } catch (Exception e) {

            } finally {
                close();
            }
            System.out.println("服务端线程完成！");
        }

        private void close() {
            if (ds != null) {
                ds.close();
                ds = null;
            }
        }

        private void exit() {
            flag = false;
            close();
        }
    }
}
